using System.Xml.Linq;
using X = Adjunct.Framework.Nuspec.XNames.Package.Metadata.FrameworkAssemblies.FrameworkAssembly;

namespace Adjunct.Framework.Nuspec
{
	/// <summary>
	/// 
	/// </summary>
	/// <remarks></remarks>
	public class NuspecFrameworkReference
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="NuspecFrameworkReference"/> class.
		/// </summary>
		/// <param name="assemblyName">Name of the assembly.</param>
		/// <param name="targetFramework">The target framework.</param>
		/// <remarks></remarks>
		public NuspecFrameworkReference(string assemblyName, string targetFramework = null)
		{
			AssemblyName = assemblyName;
			TargetFramework = targetFramework;
		}

		/// <summary>
		/// Gets or sets the name of the assembly.
		/// </summary>
		/// <value>The name of the assembly.</value>
		/// <remarks></remarks>
		public string AssemblyName { get; set; }

		/// <summary>
		/// Gets or sets the target framework.
		/// </summary>
		/// <value>The target framework.</value>
		/// <remarks></remarks>
		public string TargetFramework { get; set; }

		/// <summary>
		/// Clones this instance.
		/// </summary>
		/// <returns></returns>
		/// <remarks></remarks>
		public NuspecFrameworkReference Clone()
		{
			return new NuspecFrameworkReference(AssemblyName, TargetFramework);
		}

		/// <summary>
		/// Performs an explicit conversion from <see cref="Adjunct.Framework.Nuspec.NuspecFrameworkReference"/>
		/// to <see cref="System.Xml.Linq.XElement"/>.
		/// </summary>
		/// <param name="frameworkReference">The framework reference.</param>
		/// <returns>The result of the conversion.</returns>
		/// <remarks></remarks>
		public static explicit operator XElement(NuspecFrameworkReference frameworkReference)
		{
			return (frameworkReference == null)
			       	? null
			       	: new XElement(X.ElementName,
			       	               frameworkReference.AssemblyName.ToXAttribute(X.AssemblyName),
			       	               frameworkReference.TargetFramework.ToXAttributeIfNotEmpty(X.TargetFramework));
		}

		/// <summary>
		/// Performs an explicit conversion from <see cref="System.Xml.Linq.XElement"/> 
		/// to <see cref="Adjunct.Framework.Nuspec.NuspecFrameworkReference"/>.
		/// </summary>
		/// <param name="element">The element.</param>
		/// <returns>The result of the conversion.</returns>
		/// <remarks></remarks>
		public static explicit operator NuspecFrameworkReference(XElement element)
		{
			if (element == null)
			{
				return null;
			}
			element.EnsureElementNameIs(X.ElementName);
			return new NuspecFrameworkReference(element.AttributeValue(X.AssemblyName), element.AttributeValue(X.TargetFramework, null));
		}
	}
}